package com.nsxy.manager.common.controllers;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;

import com.nsxy.manager.common.utils.Constants;
import com.nsxy.manager.common.utils.StringEscapeEditor;
import com.nsxy.manager.user.beans.Account;
import com.nsxy.manager.user.beans.User;
import com.nsxy.manager.user.service.IAccountService;
import com.nsxy.manager.user.service.IUserService;

/**
 * @author 潜行的青衣
 * @see
 */
public class BaseController {

	protected final Logger log = LogManager.getLogger(this.getClass());
	
	@Autowired
	protected Environment env;
	
	@Resource
	private IAccountService accountService;
	
	@Resource
	private IUserService userService;
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(String.class, new StringEscapeEditor());
	}
	
	@ExceptionHandler
    public String exception(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {
        //未认证
        if(e instanceof UnauthenticatedException) {
        	return new StringBuilder()
        			.append("redirect:")
        			.append(env.getProperty("shiro.login.url")).toString();
        } else if(e instanceof UnauthorizedException) {
        	//没有权限
        	return new StringBuilder()
        			.append("redirect:")
        			.append(env.getProperty("shiro.unauthorized.url")).toString();
        }
        this.log.error("异常捕捉：", e);
        return "errors/500";  
    } 
	
	public boolean hasRole(String roleIdentifier) {
		return SecurityUtils.getSubject().hasRole(roleIdentifier);
	}
	
	public boolean isPermitted(String permission) {
		return SecurityUtils.getSubject().isPermitted(permission);
	}
	
	public Account getLoginAccount() {
		return (Account) SecurityUtils.getSubject().getPrincipal();
	}
	
	public User getLoginUser(HttpServletRequest request) {
		User user = (User) request.getAttribute(Constants.LOGIN_USER_KEY);
		if(user == null) {
			Account account = this.getLoginAccount();
			if(account != null) {
				user = this.userService.findOne(account.getId());
				request.setAttribute(Constants.LOGIN_USER_KEY, user);
			}
		}
		return user;
	}
}
